package com.woniu.servicepay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.woniu.servicepay.config.AlipayConfig;
import com.woniu.servicepay.config.PayMQConfig;
import com.woniu.servicepay.service.AlipayService;
import com.woniu.servicepay.util.PaymentWebSocketHandler;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Log4j2
public class AlipayServiceImpl implements AlipayService{
    private static Logger logger = LoggerFactory.getLogger(AlipayService.class);
    @Autowired
    AlipayConfig alipayConfig;

//    @Autowired
//    RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    private DefaultAlipayClient client() throws AlipayApiException {
        return new DefaultAlipayClient(alipayConfig);
    }

    @Override
    public String appPay(String subject, String outTradeNo, String totalAmount) {
        try {
            AlipayClient alipayClient = client();
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            request.setNotifyUrl(alipayConfig.getNotifyUrl());

            JSONObject bizContent = new JSONObject();
            bizContent.put("subject",subject);
            bizContent.put("out_trade_no",outTradeNo);//订单号
            bizContent.put("total_amount",totalAmount);
            bizContent.put("product_code","QUICK_WAP_WAY");//手机网页支付

            request.setBizContent(bizContent.toString());
            logger.info("支付宝请求参数: {}", request.getBizContent());
            return alipayClient.pageExecute(request,"get").getBody();

        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("创建支付宝支付失败", e);
        }
    }

    @Override
    public String orderNotify(HttpServletRequest request) {
        //支付宝回调信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        String orderId = params.get("out_trade_no");
        logger.info("订单号:" + orderId);
//        RLock notifylock = redissonClient.getLock("alipay:notify:" + orderId);
//        notifylock.lock();
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());
            if (flag) {
                logger.info("支付回调信息:" + params);
                rabbitTemplate.convertAndSend(PayMQConfig.PAY_EXCHANGE, "payment.handling", orderId);
                //通知前端，跳转ui（使用websocket）
                notifyFrontend( params);
                return "success";
            } else {
                return "error";
            }
        } catch (AlipayApiException e) {
            logger.error("支付宝错误回调:" + e.getErrMsg());
            e.printStackTrace();
            return "error";
        }
    }

    private void notifyFrontend(Map<String, String> params) {
        // 通过WebSocket通知前端
        PaymentWebSocketHandler.sendPaymentNotification(params);
    }
}
